package com.itheima.service;

import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class UserServiceTest {
    private SqlSession sqlSession;

    @Before
    public void init() throws IOException {
        // 加载核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");

        // 获取SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // 获取SqlSessionFactory
        SqlSessionFactory factory = builder.build(in);

        // 获取连接SqlSession
        sqlSession = factory.openSession();
    }

    @After
    public void close() {
        // 提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
    }

    @Test
    public void findByCondition(){
        // 获取Mapper的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        // 调用代理对象方法
        User user = new User();
        user.setName("haha");
        user.setAge(29);

        User u = mapper.findByCondition(user);
        System.out.println(u);
    }

    @Test
    public void findById(){
        // 获取Mapper的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        // 调用代理对象方法
        User user = mapper.findById(1);
        System.out.println(user);
    }

    @Test
    public void findByIds(){
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.findByIds(ids);
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void update(){
        User user = new User();
        user.setId(9);
        user.setName("哈哈哈");
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.update(user);
    }
}
